//
// 嗨~ o(*￣▽￣*)ブ
// Created by Mokou on 2020/7/14.
//

#import <AdSupport/ASIdentifierManager.h>
#import "Util.h"
#import "GlobalData.h"
#import <Bugly/Bugly.h>
#import "UIView+LayerEffects.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <NetworkExtension/NetworkExtension.h>

@implementation Util

+ (NSString *)getSystemVersion {
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)getAppVersion {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

+ (NSString *)getIDFA {
    NSUUID *adId = [[ASIdentifierManager sharedManager] advertisingIdentifier];
    return [adId UUIDString];
}

+ (void)showSysOption {
//    NSString *CFBundleIdentifier = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    if (@available(iOS 10, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:nil completionHandler:nil];
    }
//    else if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"prefs:root=%@", CFBundleIdentifier]]]) {
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"prefs:root=%@", CFBundleIdentifier]]];
//    }
}

+ (void)showSysTel:(NSString *)number {
    if (![self checkDefined:number]) {
        number = @"";
    }
    NSString *telNumber = @"";
    if ([number.lowercaseString hasPrefix:@"tel:"]) {
        telNumber = [NSString stringWithFormat:@"%@", number.lowercaseString];
    } else {
        telNumber = [NSString stringWithFormat:@"tel:%@", number];
    }

    NSURL *aURL = [NSURL URLWithString:telNumber];
    if ([[UIApplication sharedApplication] canOpenURL:aURL]) {
        if ([[Util getSystemVersion] floatValue] >= 10) {
            [[UIApplication sharedApplication] openURL:aURL options:nil completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:aURL];
        }
    }
}

+ (void)initBugly {
    [Bugly startWithAppId:@"25a22e5e68"];
}

+ (void)localStorage_insert_string:(NSDictionary *)data {
    NSArray *keys = data.allKeys;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    id obj = [defaults objectForKey:localStorage_key];
    NSMutableDictionary *data_tmp = NSMutableDictionary.new;

    if ([Util checkDefined:obj]) {
        NSDictionary *dict = obj;
        data_tmp = [[NSMutableDictionary alloc] initWithDictionary:dict];
    }

    for (NSString *key in keys) {
        if ([Util notNull:data k:key]) {
            data_tmp[key] = data[key];
        }
    }

    [defaults setObject:data_tmp forKey:localStorage_key];
    [defaults synchronize];
}

+ (void)localStorage_insert_int:(NSDictionary *)data {
    [Util localStorage_insert_string:data];
}

+ (void)localStorage_delete:(NSString *)key {
    if (![Util checkDefined:key]) return;

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    id obj = [defaults objectForKey:localStorage_key];

    if (![Util checkDefined:obj]) return;

    NSMutableDictionary *data_tmp = [[NSMutableDictionary alloc] initWithDictionary:obj];
    [data_tmp removeObjectForKey:key];

    [defaults setObject:data_tmp forKey:localStorage_key];
    [defaults synchronize];
}

+ (void)localStorage_update:(NSDictionary *)data {
    [Util localStorage_insert_string:data];
}

+ (NSString *)localStorage_select_string:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    id obj = [defaults objectForKey:localStorage_key];
    if (![Util checkDefined:obj]) return nil;

    NSDictionary *data_tmp = obj;
    if ([Util notNull:data_tmp k:key]) {
        return data_tmp[key];
    } else {
        return nil;
    }
}

+ (int)localStorage_select_int:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    id obj = [defaults objectForKey:localStorage_key];
    if (![Util checkDefined:obj]) return 0;

    NSDictionary *data_tmp = obj;
    if ([Util notNull:data_tmp k:key]) {
        return [data_tmp[key] intValue];
    } else {
        return 0;
    }
}

+ (NSString *)getUUID {
    return NSUUID.new.UUIDString;
}

+ (BOOL)checkDefined:(id)id {
    return id && ![id isKindOfClass:[NSNull class]];
}

+ (BOOL)notNull:(NSDictionary *)dict k:(NSString *)key {
    return [Util checkDefined:dict] && [Util checkDefined:key] && [Util checkDefined:dict[key]];
}

+ (BOOL)isDict:(id)data {
    return [data isKindOfClass:[NSDictionary class]];
}

+ (BOOL)isString:(id)data {
    return [data isKindOfClass:[NSString class]];
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentVCFrom:[(UITabBarController *) rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]) {
        currentVC = [self getCurrentVCFrom:[(UINavigationController *) rootVC visibleViewController]];
    } else {
        currentVC = rootVC;
    }
    return currentVC;
}

+ (UIViewController *)getCurrentVC {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}


+ (NSDictionary *)callBackJson:(id)data {
    if ([Util checkDefined:data]) {
        return @{@"data": data};
    } else {
        return @{};
    }
}

+ (NSDictionary *)callBackJson_select:(NSArray *)data total:(int)total isOver:(BOOL)isOver {
    if ([Util checkDefined:data]) {
        return @{@"data": data, @"total": @(total), @"isOver": @(isOver)};
    } else {
        return @{@"data": @[], @"total": @(total), @"isOver": @(isOver)};
    }
}

+ (CGFloat)sc_w {
    return [UIScreen mainScreen].bounds.size.width;
}

+ (CGFloat)sc_h {
    return [UIScreen mainScreen].bounds.size.height;
}

+ (CGFloat)px:(CGFloat)dp {
    return [self sc_w] * dp / 414.f;
}

+ (NSString *)wifiName {
    NSArray *wifiNameArr = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
    for (NSString *wfName in wifiNameArr) {
        info = (__bridge_transfer id) CNCopyCurrentNetworkInfo((CFStringRef) wfName);
        if (info && [info count]) {
            break;
        }
    }
    NSDictionary *dic = (NSDictionary *) info;
    return dic[@"SSID"];
}

+ (NSAttributedString *)getAttributedStringWithString:(NSString *)string lineSpace:(CGFloat)lineSpace {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; // 调整行间距
    NSRange range = NSMakeRange(0, [string length]);
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    return attributedString;
}

+ (CGFloat)getHeightForString:(NSString *)str lineSpacing:(CGFloat)lineSpacing fontSize:(CGFloat)size andWidth:(CGFloat)width {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:size];
    label.text = str;
    label.attributedText = [self getAttributedStringWithString:str lineSpace:lineSpacing];
    CGSize sizeToFit = [label sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)];
    return sizeToFit.height;
}

+ (void)toast:(NSString *)msg {
    if (![self checkDefined:msg]) {
        msg = @"empty text";
    }

    CGFloat fontSize = [self px:16];
    CGFloat width = [self sc_w] * 0.7F;
    CGFloat height = [self getHeightForString:msg lineSpacing:0 fontSize:fontSize andWidth:width];

    UIView *toast = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [self sc_w] * 0.8F, height + [self px:40])];
    toast.center = CGPointMake([self sc_w] / 2, [self sc_h] / 2);
    toast.backgroundColor = [UIColor blackColor];
    [toast setCornerRadius:[self px:5]];

    UILabel *toastLabel = [[UILabel alloc] initWithFrame:CGRectMake([self sc_w] * 0.05F, 0, width, toast.height)];
    toastLabel.font = [UIFont systemFontOfSize:[self px:16]];
    toastLabel.textColor = [UIColor whiteColor];
    if (height >= fontSize * 2) {
        toastLabel.textAlignment = NSTextAlignmentLeft;
    } else {
        toastLabel.textAlignment = NSTextAlignmentCenter;
    }
    toastLabel.text = msg;
    toastLabel.numberOfLines = 0;
    [toast addSubview:toastLabel];
    [[self getCurrentVC].view addSubview:toast];
    //显示动画
    toast.alpha = 0.1;
    [UIView animateWithDuration:0.4 animations:^{
        toast.alpha = 1;
    }                completion:^(BOOL finished) {
    }];

    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        usleep(2000000);
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.5 animations:^{
                toast.alpha = 0;
            }                completion:^(BOOL finished) {
                [toast removeFromSuperview];
            }];
        });
    });
}

+ (long long int)now {
    return (long long int) ([[NSDate date] timeIntervalSince1970] * 1000L);
}

+ (NSString *)getAbsolutePath:(NSString *)relativePath {
    return [NSHomeDirectory() stringByAppendingPathComponent:relativePath];
}

+ (void)alertNeedLocationAuthorization {
    NSString *tip = @"请点击设置开启定位权限\n";
    if(@available(iOS 14, *)) {
        tip = [tip stringByAppendingString:@"点击'位置'->'使用App期间'\n并开启'精确位置'"];
    } else {
        tip = [tip stringByAppendingString:@"点击'位置'->'使用App期间'进行设置"];
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:tip preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [Util showSysOption];
    }];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        UIAlertController *alert_noAuth = [UIAlertController alertControllerWithTitle:@"提示" message:@"未开启定位权限" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *conform_noAuth = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
        [alert_noAuth addAction:conform_noAuth];
        [[Util getCurrentVC] presentViewController:alert_noAuth animated:YES completion:nil];
    }];

    [alert addAction:conform];
    [alert addAction:cancel];

    [[Util getCurrentVC] presentViewController:alert animated:YES completion:nil];
}

//+ (void)post:(NSString *)urlStr data:(NSDictionary *)data {
//    NSURL *url = [NSURL URLWithString:urlStr];
//    NSMutableURLRequest *requestPost =[NSMutableURLRequest requestWithURL:url];
//    [requestPost setHTTPMethod:@"POST"];
//    NSDictionary *parameters;
//    if([Util checkDefined:data]) {
//        parameters = data;
//    } else {
//        parameters = @{};
//    }
//    NSError *error;
//    [requestPost setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted  error:&error]];
//    [requestPost setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-type"];
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:requestPost completionHandler:nil];
//    [sessionDataTask resume];
//}

@end
